use super::models::*;
use actix_web::cookie::time::Date;
use chrono::NaiveDateTime;
use sqlx::mysql::MySqlPool;
use sqlx::Row;

pub async fn get_courses_for_teacher_db(pool: &MySqlPool, teacher: i32) -> Vec<Course> {
    let rows = sqlx::query("select id, teacher_id, name, time")
        .fetch_all(pool)
        .await
        .unwrap();


    rows.iter()
        .map(|r: &sqlx::mysql::MySqlRow| Course {
            id: r.id,
            teacher_id: r.teacher_id,
            name: r.name.clone(),
            time: Some(NaiveDateTime::from(r.time.unwrap())),
        }).collect()
}

pub async fn get_course_details_db(pool: &MySqlPool,teacher_id: i32,course_id: i32) -> Course{
    let row =  sqlx::query("select id, teacher_id,name,time
           from course where teacher_id = $1 and id = $2")
           .fetch_one(pool)
           .await
           .unwrap();
    Course {
        id: row.get::<i32, &str>("id"),
        teacher_id: row.get::<i32, &str>("teacher_id"),
        name: row.get::<String, &str>("name"),
        time: row.get::<NaiveDateTime, &str>("time")
    }
}

pub async fn post_new_courses_db(pool: &MySqlPool,new_course: Course) -> Course {
    let row = sqlx::query("insert into course (id,teacher_id,name) values
            ($1,$2,$3) RETURNING id, teacher_id, name, time",new_course.id, new_course.teacher_id,new_course.name)
            .fetch_all(pool)
            .await
            .unwrap();
    Course {
        id: row.get::<i32, &str>("id"),
        teacher_id: row.get::<i32, &str>("teacher_id"),
        name: row.get::<String, &str>("name"),
        time: Some(NaiveDateTime::from(row.get::<Date, &str>("time")))
    }
}